from app.account.models import EmailVerifyRecord
from rest_framework.views import APIView
from django.http import JsonResponse
from django.core.mail import send_mail
from common.authCheck.userAuth import check_login
from AoDuoServer.settings import DEFAULT_FROM_EMAIL
from random import Random


def random_str(randomInt=20):
    ran_str = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomInt):
        ran_str += chars[random.randint(0, length)]
    return ran_str


class SendEmailView(APIView):

    @check_login
    def get(self, request, send_type):
        """
        发送验证码邮件
        :param request:
        :param send_type:
        :return:
        """
        code = random_str()
        email = request.session.get('login')
        email_record = EmailVerifyRecord.objects.create(
            code=code,
            email=email,
            send_type=send_type,
        )
        if send_type == 'active':
            email_title = '注册激活链接'
            email_body = '请点击下面的链接激活您的邮箱http://127.0.0.1:8000/user/active/{0}'.format(code)
        elif send_type == 'forget':
            email_title = '充值密码链接'
            email_body = '请点击下面的链接激活您的邮箱http://127.0.0.1:8000/user/reset/{0}'.format(code)
        else:
            return JsonResponse({
                'status': False,
                'errMsg': '参数错误'
            }, status=403)
        send_status = send_mail(email_title, email_body, DEFAULT_FROM_EMAIL, [email])
        if send_status:
            return JsonResponse({
                'status': True,
                'eid': email_record.id
            })
        return JsonResponse({
            'status': False,
            'errMsg': '邮件发送失败'
        }, status=401)